<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("模板分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" :content="$t('设置')" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <div class="l-rblock" style="padding-bottom: 32px">
          <div class="l-rblock" style="overflow: hidden auto">
            <el-tree
              v-loading="treeLoading"
              :data="treeShowData"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <span class="lr-tree-node" slot-scope="{ node }">
                <i class="el-icon-notebook-2"></i>
                {{ node.label }}
              </span>
            </el-tree>
          </div>
          <div class="l-bottom">
            <el-input
              :placeholder="$t('please enter名称')"
              @keyup.enter.native="hanleSearchCategory"
              v-model="searchCategoryWord"
              size="mini"
            >
              <el-button
                @click="hanleSearchCategory"
                slot="append"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </div>
        </div>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('please enter名称')"
            @keyup.enter.native="hanleSearch"
            v-model="keyWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()" btnText="Add">
          <el-button-group
            ><l-file-import
              fileType="json"
              classname="printtemplateimport"
              @success="exportSuccess()"
            ></l-file-import
          ></el-button-group>
        </l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="columns"
        :dataSource="tableData"
        row-key="F_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:f_EnabledMark="scope">
          <el-tag v-if="scope.row.f_EnabledMark === 2" size="mini">{{ $t('草稿') }}</el-tag>
          <el-switch
            v-else
            v-model="scope.row.f_EnabledMark"
            :active-value="1"
            :inactive-value="0"
            @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <l-table-btns
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>
    <l-fullscreen-dialog
      title="打印模板"
      :visible.sync="formVisible"
      ref="formDialog"
      @opened="handleOpenedForm"
      @close="handleCloseForm"
      @ok="
        (showLoading, hideLoading) => handleSave(showLoading, hideLoading, 1)
      "
    >
      <template #headerRight>
        <el-button size="mini" type="warning" @click="handleSaveDraft">{{
          $t("暂存")
        }}</el-button>
      </template>
      <print-form ref="form"></print-form>
    </l-fullscreen-dialog>
    <!-- 分类管理 -->
    <l-drawer
      :title="$t('分类管理')"
      :visible.sync="categoryVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <l-dataitem-index classifyCode="printSort"></l-dataitem-index>
    </l-drawer>
    <!-- 历史记录 -->
    <l-drawer
      :title="`${$t('历史记录')}-${$t(historyTitle)}`"
      :visible.sync="historyVisible"
      :showOk="false"
      :showClose="false"
      size="640px"
      @opened="HistoryOpened"
    >
      <history
        ref="HistoryForm"
        :schemeInfoId="schemeInfoId"
        :schemeId="schemeId"
        :updateSchemeId="updateSchemeId"
        :historyVisible.sync="historyVisible"
        @loadTablePageIndexData="loadTablePageData"
      ></history>
    </l-drawer>
  </l-layout>
</template>

<script>
import PrintForm from "./form";
import history from "./history";
const api = window.$api.print.printTemplate;
export default {
  components: {
    PrintForm,
    history,
  },
  props: {
    menu: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      treeLoading: false,
      treeData: [],
      treeShowData: [],
      vueOption: {},
      tableData: [],
      formEdit: false,
      formEditRow: null,
      keyWord: "",
      tableLoading: false,
      tableTotal: 0,
      tableCurrentPage: 1,
      // 表格
      columns: [
        { label: "编码", prop: "f_Code", width: "150" },
        { label: "名称", prop: "f_Name", minWidth: "150" },
        {
          label: "分类",
          prop: "f_Category",
          minWidth: "150",
          dataType: "dataItem",
          dataCode: "printSort",
        },
        { label: "状态", prop: "f_EnabledMark", minWidth: "150" },
        { label: "创建人", prop: "f_CreateUserName", minWidth: "150" },
        {
          label: "创建时间",
          prop: "f_CreateDate",
          minWidth: "150",
          dataType: "datetime",
        },
      ],
      tableBtns: [
        { prop: "Edit", label: this.$t("Edit"),width:40 },
        { prop: "History", label: this.$t("历史记录"),width:60 },
        { prop: "Delete", label: this.$t("Delete") },
        { prop: "Export", label: this.$t("导出") },
        { prop: "Copy", label: this.$t("复制") },
      ],
      preVisible: false,
      categoryVisible: false,
      categoryId: "",
      searchCategoryWord: "",
      formVisible: false,
      formTitle: "",
      tablePageSize: 50,
      type: 0,
      historyTitle: "",
      historyVisible: false,
      schemeInfoId: "",
      schemeId: "",

      formCopy:false//复制操作
    };
  },
  mounted() {
    this.lr_loadDataItem("printSort");
    this.loadTablePageData();
  },
  watch: {
    dataItemTree_Function: {
      handler(n) {
        this.treeData = n;
        this.treeShowData = n;
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    dataItemTree_Function() {
      return this.lr_dataItemTree(this.lr_dataItem["printSort"]);
    },
  },
  methods: {
    refreshCategory(data) {
      this.searchCategoryWord = "";
      this.treeData = [];
      data.forEach((item) => {
        this.treeData.push({ value: item.value, label: item.label });
      });
      this.treeShowData = this.treeData;
    },
    hanleSearch() {
      this.loadTablePageData();
    },
    loadTablePageData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx:'f_CreateDate DESC',
        F_Category: this.categoryId,
        keyword: this.keyWord,
      };
      api
        .getPage(queryData)
        .then((res) => {
          const tableData = this.$deepClone(res.data.data);
          this.tableData = tableData.rows;
          this.tableTotal = tableData.records;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    handleAdd() {
      this.formEdit = false;
      this.formCopy = false;
      this.showForm("Add");
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePageData(true);
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.formCopy = false;
      this.showForm("Edit");
    },
    handleDelete($index, row) {
      this.$confirm(this.$t("This operation will permanently delete the data. Do you want to continue?"), this.$t("Tips"), {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning",
      }).then(() => {
        api
          .remove(row.f_Id)
          .then(() => {
            this.$message({
              type: "success",
              message: this.$t("Delete  success"),
            });
            this.loadTablePageData();
          })
          .catch(() => {});
      });
    },
    handleHistory($index, row) {
      this.formEditRow = row;
      this.historyTitle = row.f_Name;
      this.schemeId = row.f_TemplateId;
      this.schemeInfoId = row.f_Id;

      this.historyVisible = true;
    },
    HistoryOpened() {
      this.$refs.HistoryForm.loadTablePageData();
    },
    updateSchemeId(id) {
      this.schemeId = id;
      this.formEditRow.f_SchemeId = id;
    },
    handleSettingClick() {
      this.categoryVisible = true;
    },
    handleNodeClick(data) {
      this.categoryId = data.value;
      this.loadTablePageData();
    },
    hanleSearchCategory() {
      if (this.searchCategoryWord) {
        this.treeShowData = this.treeData.filter(
          (item) => item.label.indexOf(this.searchCategoryWord) > -1
        );
      } else {
        this.treeShowData = this.treeData;
      }
    },
    showForm(text) {
      this.loadCategory();
      this.formTitle = text;
      this.formVisible = true;
    },
    loadCategory() {
      this.treeData = [];
      this.lr_dataItemTree(this.lr_dataItem["printSort"]).forEach((item) => {
        this.treeData.push({ value: item.value, label: item.label });
      });
    },
    handleSaveDraft() {
      this.handleSave(
        this.$refs.formDialog.showLoading,
        this.$refs.formDialog.hideLoading,
        2
      );
    },
    async handleSave(showLoading, hideLoading, type) {
      showLoading("saving data...");
      if (await this.$refs.form.validateForm()) {
        const res = await this.$refs.form.saveForm({
          keyValue: this.formEdit ? this.formEditRow.f_Id : "",
          isEdit: this.formEdit,
          type: type,
        });
        if (res) {
          const msg = this.formEdit ? this.$t("更新成功!") : this.$t("Add成功!");
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.loadTablePageData();
          this.formVisible = false;
        }
      }
      hideLoading();
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit||this.formCopy) {
        showLoading("Loading data...");
        await this.$refs.form.loadFormData({
          keyValue: this.formEditRow.f_Id,
          formCopy: this.formCopy
        });
        hideLoading();
      }
    },
    //打印模板的导出
    handleExport($index, row) {
      this.lr_downTempFile(
        `print/printTemplate/download/printTemplate/${row.f_Id}`,
        `${this.$t('打印设计_通用模板')}_${row.f_Name}`,
        "printTemplate",
        "json"
      );
    },
    exportSuccess() {
      this.loadTablePageData();
    },
    //表单设计的复制
    handleCopy($index, row) {
      this.formEdit = false;
      this.formCopy = true;
      this.formEditRow = row;
      this.showForm();
    },
    // 更新状态
    handleEnableChange(row){
      api.updateState(row.f_EnabledMark,row.f_Id).then(() => {
        this.$message({
          type: "success",
          message: this.$t("更新成功!"),
        });
      });
    }
  },
};
</script>
